package mblog.base.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Project  : mblog
 * Author   : Wu Tian Qiang
 * Date     : 2016/8/1
 */
public class WeiBoUtils {
    private static String app_secret = "15348f0a8d6dfcea5a67567371b4150a"; //appkey对应的secret，验证签名时使用。
    private static String access_token = "2.00lzlsSE0n4HTXf7bd7066f7oc8FGC";

    /**
     * 验证sha1签名，验证通过返回true，否则返回false
     *
     * @param signature
     * @param nonce
     * @param timestamp
     * @return
     */
    public static boolean vlidateSHA(String signature, String nonce, String timestamp) {
        if (signature == null || nonce == null || timestamp == null) {
            return false;
        }
        String sign = sha1(getSignContent(nonce, timestamp, app_secret));
        if (!signature.equals(sign)) {
            return false;
        }
        return true;
    }

    /**
     * 生产sha1签名
     *
     * @param strSrc
     * @return
     */
    private static String sha1(String strSrc) {
        MessageDigest md = null;
        String strDes = null;

        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            //TODO
            e.printStackTrace();
        }
        return strDes;
    }

    private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;

        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));

            if (tmp.length() == 1) {
                des += "0";
            }

            des += tmp;
        }

        return des;
    }


    /**
     * 对非空参数按字典顺序升序构造签名串
     *
     * @param params
     * @return
     */

    private static String getSignContent(String... params) {
        List<String> list = new ArrayList(params.length);
        for (String temp : params) {
            if (StringUtils.isNotBlank(temp)) {
                list.add(temp);
            }
        }
        Collections.sort(list);
        StringBuilder strBuilder = new StringBuilder();
        for (String element : list) {
            strBuilder.append(element);
        }
        return strBuilder.toString();
    }


    /**
     * 发送的消息
     *
     * @param msg
     * @param receiverId
     */
    public static void sendTextMsg(String msg, Long receiverId) {
        JSONObject o = new JSONObject();
        o.put("text", msg);
        sendMsg(o.toJSONString(), "text", receiverId);
    }


    /**
     * 主动推送消息给用户
     *
     * @param msgJSON    消息内容  json格式
     * @param receiverId
     */
    public static void sendMsg(String msgJSON, String type, Long receiverId) {
        System.out.println(msgJSON);
        String url = "https://m.api.weibo.com/2/messages/reply.json";

        Map<String, Object> params = new HashMap<>();
        params.put("access_token", access_token);
        params.put("type", type);
        params.put("receiver_id", receiverId);
        params.put("save_sender_box", 1);
        try {
            params.put("data", URLEncoder.encode(msgJSON, "utf-8")); //data字段的内容需要进行utf8的urlencode
            System.out.println(params);
            CHttpUtils.doPost(url, params, 60000, 60000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 回复Text 消息
     *
     * @param data
     * @return
     */
    public static String replyTextMsg(String data, Long senderId, Long receiverId) {
        JSONObject o = new JSONObject();
        o.put("text", data);
        return generateReplyMsg(o.toJSONString(), "text", senderId, receiverId);
    }

    /**
     * 生成回复的消息。（发送被动响应消息）
     *
     * @param data       消息的内容。
     * @param type       消息的类型
     * @param senderId   回复消息的发送方uid。蓝v用户自己
     * @param receiverId 回复消息的接收方  蓝v用户的粉丝uid
     * @return
     */
    public static String generateReplyMsg(String data, String type, Long senderId, Long receiverId) {
        JSONObject jo = new JSONObject();
        jo.put("result", true);
        jo.put("sender_id", senderId);
        jo.put("receiver_id", receiverId);
        jo.put("type", type);
        try {
            jo.put("data", URLEncoder.encode(data, "utf-8")); //data字段的内容需要进行utf8的urlencode
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jo.toString();
    }


    public static void main(String[] args) {
        sendTextMsg("闲适看电影，愉悦好心情！", 2516987983l);
    }

}
